import {
    Button,
    DatePicker,
    Input,
    Radio,
    Select,
    Switch,
} from '@arco-design/web-react'
import { IconSync } from '@arco-design/web-react/icon'
import React from 'react'
import { IVariableItem, IVariableValueType } from '@/utils/interfaces'
import { mock } from '@/utils/mock'
import { variableTypeHandlers } from '@/utils/variableHandlers'

export interface IVariableValueProps {
    // 变量值
    variableItem?: IVariableItem
    // 输入值
    value?: IVariableValueType
    // 变化时
    onChange?: (value: IVariableValueType) => void
}

const VariableValue: React.FC<IVariableValueProps> = ({
    variableItem,
    value: propsValue,
    onChange: propsOnChange,
}) => {
    // 输入框的值
    // const [value, setValue] = useState(propsValue)
    // mock模板cache

    // 值变化
    const handleChange = (value: IVariableValueType) => {
        const type = variableItem?.type

        if (!type) {
            propsOnChange?.(value)
            return
        }

        const newValue = variableTypeHandlers[type](value)

        propsOnChange?.(newValue)
    }

    // 随机生成值
    const handleRandom = () => {
        const item = variableItem

        if (!item?.mockRule) {
            return
        }
        console.log('mock', item)
        const newValue = mock(item.mockRule, {
            noJsonParse: true,
            noJsonStringify: true,
        })
        console.log('newValue', newValue)
        if (newValue === undefined) {
            return
        }
        handleChange(newValue)
    }

    // useEffect(() => {
    //     setValue(propsValue)
    // }, [propsValue])

    const renderInputComp = () => {
        // 默认，输入框
        const defaultComp = (
            <Input
                allowClear
                value={propsValue as string | undefined}
                onChange={handleChange}
            />
        )

        // 获取类型
        const type = variableItem?.type
        if (type) {
            if (type === 'null') {
                return 'null'
            } else if (type === 'boolean') {
                return (
                    <Switch
                        checked={!!propsValue}
                        onChange={(v) => handleChange(!!v)}
                    />
                )
            }
        }

        // type 是 string 和 number 的情况

        // 获取mock规则
        const mockRule = variableItem?.mockRule
        if (!mockRule) {
            return defaultComp
        }

        // 如果是日期类型
        // if (mockRule.includes('@date') || mockRule.includes('@time')) {
        //     // 现在是 @date @datetime @time类型
        //     // 获取括号内的参数，括号内的参数
        //     return (
        //         <DatePicker
        //             showTime
        //             format='YYYY-MM-DD HH:mm:ss'
        //             value={propsValue as string | undefined}
        //             onChange={handleChange}
        //         />
        //     )
        // }

        // 如果是boolean类型
        if (mockRule.includes('@boolean')) {
            let val = propsValue
            if (type) {
                if (type === 'string') {
                    val = val === 'true'
                } else if (type === 'number') {
                    val = !!(Number(val) || parseInt(val?.toString() || ''))
                }
            } else {
                val = !!val
            }

            return (
                <Switch
                    checked={val as boolean}
                    onChange={(v) => handleChange(!!v)}
                />
            )
        }

        // 如果是 pick 类型
        if (mockRule.includes('@pick')) {
            // 获取括号内的参数
            const rule = mockRule
            const params = rule.match(/\((.*)\)/)?.[1]
            if (!params) {
                return defaultComp
            }

            // 获取参数列表
            const paramsList = params.split(',').map((item) => item.trim())

            // 获取选中的参数
            if (paramsList.length <= 0) {
                return defaultComp
            }

            if (paramsList.length <= 2) {
                return (
                    <Radio.Group value={propsValue} onChange={handleChange}>
                        {paramsList.map((item, index) => (
                            <Radio key={item + index} value={item}>
                                {item}
                            </Radio>
                        ))}
                    </Radio.Group>
                )
            } else {
                return (
                    <Select
                        allowClear
                        value={propsValue as string | number | undefined}
                        onChange={handleChange}
                        options={paramsList.map((item) => ({
                            label: item,
                            value: item,
                        }))}
                    />
                )
            }
        }

        return defaultComp
    }

    return (
        <div>
            <div className='flex'>
                {renderInputComp()}
                {!!variableItem?.mockRule && (
                    <Button
                        className='shrink-0 ml-2'
                        icon={<IconSync />}
                        onClick={() => handleRandom()}
                    />
                )}
            </div>
            {/* <div>{propsValue + ''}</div> */}
        </div>
    )
}

export default VariableValue
